import asyncio
import json
import threading

import websockets

# 给变量加锁
lock = threading.Lock()
loop = None
server = None
response = []
connection = 0


def send_message(message):
    if connection > 0:
        lock.acquire()
        response.append(message)
        lock.release()


def del_message(message):
    lock.acquire()
    response.remove(message)
    lock.release()


def clear_message():
    global response
    lock.acquire()
    response = []
    lock.release()


# 定义服务端接收请求的处理方法
async def serve(websocket, path):
    from bilibili import set_flag
    global connection
    connection += 1
    print("New client connected")
    try:
        while True:
            if len(response) > 0:
                message = response[0]
                Id = message['Id']
                Nickname = message['Nickname']
                Content = message['Content']
                timeline = message['timeline']
                new_message = {
                    'User': {
                        'Id': Id,
                        'Nickname': Nickname
                    },
                    'Content': Content,
                    'timeline': timeline
                }
                new_message = {
                    'Type': 1,
                    'Data': str(new_message).replace("'", r'"')
                }
                new_message = json.dumps(new_message, ensure_ascii=False)
                await websocket.send(new_message)
                print(f"Send message: {new_message}")
                del_message(message)
            await asyncio.sleep(0.05)
    except websockets.exceptions.ConnectionClosedOK:
        print("Client disconnected")
    except Exception as e:
        print(e)
    finally:
        if connection > 0:
            connection -= 1
        print(f'当前连接数{connection}')
        if connection == 0:
            clear_message()
            set_flag(False)
            print('已清空消息列表')


def ws_open_server():
    global loop, server, connection
    connection = 0
    # 在新线程中创建一个新的 event loop
    loop = asyncio.new_event_loop()
    asyncio.set_event_loop(loop)
    # 创建 WebSocket 服务端
    server = websockets.serve(serve, "localhost", 25565)
    print("websocket服务端已开启")

    # 启动服务端
    loop.run_until_complete(server)
    loop.run_forever()
    print('websocket服务端已关闭')


def ws_close_server():
    global loop, server
    if server is not None:
        server.ws_server.close()
        loop.call_soon_threadsafe(loop.stop)
        # loop.close()
        # loop = None
        print("尝试关闭websocket服务端")

